package cn.jingzhuan.element.demo.view.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.AdapterView
import android.widget.BaseAdapter

/**
 * Recycler分页数据
 */
abstract class PageRecyclerAdapter<T>(var mContext: Context,var list: MutableList<T>?,var pageSize:Int): RecyclerView.Adapter<PageRecyclerViewHolder>() {

    private val mInflater: LayoutInflater = LayoutInflater.from(mContext)

    abstract fun getRootLayoutId(viewType: Int): Int
    abstract fun bindData(data: T,convertView:View?,parent:ViewGroup?): View
    abstract fun onItemClickListener(datas: MutableList<T>?):AdapterView.OnItemClickListener


    // 获取总页数
    override fun getItemCount(): Int  {
        var itemCount =  list?.size?.div(pageSize)!!.plus(if(list!!.size.rem(pageSize) > 0) 1 else 0)
        return itemCount
    }

    // 创建视图
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageRecyclerViewHolder {
        var rootView = mInflater.inflate(getRootLayoutId(viewType) , parent, false) as AbsListView

        return PageRecyclerViewHolder(mContext,rootView)
    }

    override fun onBindViewHolder(holder: PageRecyclerViewHolder, position: Int) {
        var begin = pageSize * position
        var end = pageSize * (position + 1)
        if (end > list!!.size) {
            end = list!!.size
        }
        var datas = list?.subList(begin,end)
        var baseAdapter =  object : BaseAdapter(){
            override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
                return bindData(getItem(position) as T,convertView,parent)
            }

            override fun getItem(position: Int): Any  = datas?.get(position) as Any

            override fun getItemId(position: Int): Long = getItem(position).hashCode().toLong()

            override fun getCount(): Int = datas!!.size

        }
        holder.bind(baseAdapter!!,onItemClickListener(datas))
    }

}